using System;
using System.Collections.Generic;
using System.Reflection;
namespace Foundry.Engine
{
	public class DispatchMethod
	{
		private MethodInfo method;
		private int hash;
		public MethodInfo Method { get { return method; } }
		
		public DispatchMethod(MethodInfo m)
		{
			hash = m.Name.GetHashCode();
			method = m;
		}
		
		public override int GetHashCode ()
		{
			return hash;
		}
	}
	
	
	public class Modifier : BaseObject
	{
		[NonSerialized]
		internal bool Initialized;
		Foundry.Engine.Node parent;
		
		private List<DispatchMethod> dispatches = new List<DispatchMethod>();
		
		private void Dispose()
		{
			
		}
		
		public void Remove()
		{
			Parent = null;
		}
		
		internal void EnumerateDispatch()
		{
			dispatches = new List<DispatchMethod>();
			var methods = GetType().GetMethods();
			
			foreach(var m in methods)
			{
				if(m.ImplementsAttribute<DispatchAttribute>())
				{
					dispatches.Add(new DispatchMethod(m));	
				}
			}
			
		}
		
		public void Dispatch(string name, params object[] arguments)
		{
			Dispatch(name.GetHashCode(), arguments);
		}
		
		public void Dispatch(int hash, params object[] arguments)
		{
			if(dispatches != null)
			{
				var d = dispatches.Find(item => item.GetHashCode() == hash);
				if(d != null)
				{
					d.Method.Invoke(this, arguments);
				}
			}
		}
		
		public Node Parent
		{
			get
			{
				return parent;
			}
			set
			{
				if(parent !=null)
					parent.RemoveChild(this);
				if(value !=null)
					value.AddChild(this);
				parent = value;
			}
		}

		public Modifier ()
		{
		}
	}
}

